<template>
  <div class="StatisticCenter">
    <Vue-Tabs-Swipe
      :value="tabCurrent"
      tab-font-weight="600"
      :tab-slider-width="50"
      border-bottom
      touch-animation
      class="tapsStyle shadow-light"
      @change="e => tabChange(e)"
    >
      <div
        v-for="(tab) in tabs"
        :key="tab.label"
        :tab-label="tab.label"
      />
    </Vue-Tabs-Swipe>
    <div class="StatisticCenter_container">
      <!-- v-if="tabCurrent === 2" -->
      <div
        v-if="false"
        class="searchFilter"
      >
        <!-- <view class="filter-icon" @click="openFilter">
        筛选
        <u-icon name="arrow-down-fill" color="#333" size="28" />
      </view> -->
        <u-search
          v-model="search"
          class="commonlist-search"
          :show-action="false"
          placeholder="搜索"
          clearable
          bg-color="#EDEDEE"
          shape="square"
          @change="filterList"
        />
      </div>
      <div class="commonlist-content">
        <!-- <Hr-Pull-Load
          ref="hrPullLoad"
          :is-allow-pull="true"
          :height="-1"
          :bottom-tips="pullConfig.bottomTips"
          :lower-threshold="pullConfig.lowerThreshold"
          @loadMore="pullConfig.loadMore"
        > -->
        <!--
          @loadMore="pullConfig.loadMore"
          @refresh="pullRefresh"
         -->
        <List-Cells
          :list="tabs[tabCurrent].dataList"
          @itemClick="cellClick"
        />
        <!-- </Hr-Pull-Load> -->
      </div>
    </div>
  </div>
</template>
<script>
import VueTabsSwipe from 'vue-tabs-swiper';
import { Message, setLocal, getLocalStorage } from '@/utils/utils';
import _ from 'lodash';
import {
  commonRequest as commonRequest1,
  findModelFormTableInfo,
  findModelInfoByFormGuid
  // myReceivedList
} from '@/api/commonlist';

const commonRequest = function(...args) {
  return commonRequest1(...args).then(res => {
    if (!res.success) {
      Message(res.message || '查询失败');
    }
    return Promise.resolve(res);
  });
};

const ListCells = {
  name: 'StatisticCenterCells',

  props: {
    list: {
      type: Array,
      defalt: () => ([])
    }
  },

  methods: {
    init() {
    }
  },

  created() {
    this.init();
  },

  render(h) {
    const CellInstance = this.list.map((cell, i) => {
      const {
        modelName,
        startedDate,
        startedUserName,
        createTime,
        approveTime,
        isApprove,
        finishStatus,
        creator
      } = cell;

      return h(
        'div',
        {
          class: {
            myCell: 1,
            'border-line': 1,
            pb: i === this.list.length - 1,
            pt: i === 0,
            'pb-s': i !== this.list.length - 1
          },
          on: {
            click: () => {
              this.$emit('itemClick', cell);
            }
          }
        },
        [
          h('div', { class: 'myCell-left' }, [
            h('div', [
              h('div',
                {
                  class: 'label'
                },
                [
                  h('div', { class: 'label_font' }, (startedUserName || creator) + '发起' + (modelName)),
                  isApprove === 1 ? h('div', {
                    class: 'cw_tip'
                  }, '流') : ''
                ])
            ]),
            h('div', {
              class: 'myCell-tip'
            }, approveTime || createTime || startedDate)
          ]),
          h('div', { class: 'myCell-right' },
            [
              h('div', {
                class: 'myCell-tag'
              }, finishStatus)
            ]
          )
        ]
      );
    });

    return (
      <div class='StatisticCell' >
        { CellInstance }
      </div>
    );
  }
};

export default {
  components: {
    VueTabsSwipe,
    ListCells
  },

  data() {
    return {
      tabCurrent: 0,
      search: '',
      tabs: [
        {
          label: '待办',
          dataList: [],
          url: 'formTask/my/todoTaskList',
          payload: {
            'assignee_names_^VLK': '',
            'task.subject_^VLK': '',
            limit: 200,
            offset: 0,
            order: 'desc',
            sort: 'task.create_time_'
          }
        },
        {
          label: '已办',
          dataList: [],
          url: 'formTask/my/approveList',
          payload: {
            'assignee_names_^VLK': '',
            'task.subject_^VLK': '',
            limit: 200,
            offset: 0,
            order: 'desc',
            sort: 'task.create_time_'
          }
        },
        {
          label: '我发起',
          url: 'modelForm/myStarted/list',
          dataList: [],
          headers: {
            // 'Content-Type': 'application/x-www-form-urlencoded'
          },
          payload: {
            order: 'desc',
            sort: 'startedDate'
          }
        },
        {
          label: '我收到',
          url: 'modelForm/myReceived/list',
          method: 'get',
          dataList: [],
          payload: {
            order: 'desc',
            sort: 'startedDate'
          }
        }
      ],

      pullConfig: {
        // 加载更多时的底部提示，‘nomore’：没有更多数据了；‘loading’：加载中...；‘more’：上拉加载更多；
        bottomTips: 'more',
        lowerThreshold: 10, // 距离组件底部多远时触发加载更多
        loadMore: this.loadMore
      }
    };
  },

  created() {
    this.init();
    this.filterList = _.debounce(this.filterList, 500);
  },

  methods: {
    cellClick(cell) {
      const {
        tabCurrent,
        willDoClick,
        alearlyDoClick,
        initiateByMyClick,
        receiveByMyClick
      } = this;

      const evtMap = {
        0: willDoClick,
        1: alearlyDoClick,
        2: initiateByMyClick,
        3: receiveByMyClick
      };

      if (tabCurrent in evtMap) {
        evtMap[tabCurrent].call(this, cell);
      }
    },

    filterList(e) {
      console.log(e);
    },

    // 待办点击
    willDoClick(item) {
      const {
        bizKey: formGuid,
        modelName,

        myQuery,
        defId,
        defKey,
        taskId,
        instId,
        sId
      } = item;

      findModelFormTableInfo({ formGuid }).then(res => {
        const { success, data } = res;
        if (success) {
          const { children } = data;
          const { isComment } = myQuery;
          const modelContent = children.find(o => o.tableName.includes('模板内容'));
          const tableIds = modelContent && modelContent.id;
          const spContent = children.find(o => o.tableName.includes('审批内容'));
          const spTableId = spContent && spContent.id;

          const query = {
            modelName,
            tableIds,
            formGuid,
            spTableId,
            defId,
            taskId,
            instId,
            sId,
            defKey,
            isComment, // 是否评论
            myType: 'myDb' // 标志我的待办
          };
          this.$router.push({
            path: '/StatisticCenterDetail',
            query
          });
        }
      });
    },

    // 已办点击
    alearlyDoClick(item) {
      const {
        bizKey: formGuid,
        modelName,

        myQuery,
        defId,
        defKey,
        taskId,
        instId,
        sId
      } = item;

      findModelFormTableInfo({ formGuid }).then(res => {
        const { success, data } = res;
        if (success) {
          const { children } = data;
          const { isComment } = myQuery;
          const modelContent = children.find(o => o.tableName.includes('模板内容'));
          const tableIds = modelContent && modelContent.id;
          const spContent = children.find(o => o.tableName.includes('审批内容'));
          const spTableId = spContent && spContent.id;

          const query = {
            modelName,
            tableIds,
            formGuid,
            spTableId,
            defId,
            taskId,
            instId,
            sId,
            defKey,
            isComment, // 是否评论
            myType: 'myDb', // 标志我的待办
            myDbType: '1' // 标志我的已办 标志我的待办基础上
          };
          this.$router.push({
            path: '/StatisticCenterDetail',
            query
          });
        }
      });
      // console.log({
      //   formGuid,

      //   myQuery,
      //   defId,
      //   defKey,
      //   taskId,
      //   instId,
      //   sId
      // });
    },

    // 我发起点击
    async initiateByMyClick(item) {
      const {
        acceptanceFormNum: formGuid,
        isApprove,
        modelName
      } = item;
      let isComment = ''; // 是否评论
      await findModelInfoByFormGuid({ formGuid }).then(res => {
        if (res.success) {
          const data = res.data;
          isComment = data.isComment;
        }
      });

      findModelFormTableInfo({ formGuid }).then(res => {
        if (res.success) {
          const {
            children
          } = res.data;

          const tableIds = children.reduce((p, c, i) => {
            const {
              id
            } = c;

            p += id;
            if (i !== children.length - 1) {
              p += ',';
            }

            return p;
          }, '');

          const query = {
            modelName,
            tableIds,
            formGuid,
            isApprove,
            isComment,
            myType: '我发起'
          };

          this.$router.push({
            path: '/StatisticCenterDetail',
            query
          });
        }
      });
    },

    // 我收到点击
    async receiveByMyClick(item) {
      const {
        acceptanceFormNum: formGuid,
        modelName
      } = item;

      let isComment = ''; // 是否评论
      await findModelInfoByFormGuid({ formGuid }).then(res => {
        if (res.success) {
          const data = res.data;
          isComment = data.isComment;
        }
      });

      findModelFormTableInfo({ formGuid }).then(res => {
        if (res.success) {
          const {
            children: children1
          } = res.data;
          const children = children1.filter(o => o.tableName.includes('模板内容'));
          const tableIds = children.reduce((p, c, i) => {
            const {
              id
            } = c;

            p += id;
            if (i !== children.length - 1) {
              p += ',';
            }

            return p;
          }, '');

          const query = {
            modelName,
            tableIds,
            formGuid,
            isComment,
            myType: '我收到'
          };

          this.$router.push({
            path: '/StatisticCenterDetail',
            query
          });
        }
      });
    },

    init() {
      const tab = getLocalStorage('StatisticCenterListTab');
      this.tabCurrent = tab || 0;
    },

    tabChange(tab) {
      setLocal({ StatisticCenterListTab: tab });
      this.tabCurrent = tab;

      this.getListData({ tab, turn: true });
    },

    getListData({ tab, turn }) {
      const tabNow = this.tabs[tab];
      const {
        url,
        method,
        dataList,
        headers,
        payload
      } = tabNow;

      if (url) {
        if (turn && dataList.length) {
          return;
        }

        const flag = [0, 1].includes(tab);

        commonRequest(payload || {}, url, method, headers).then(async(res) => {
          if (res.success) {
            const data1 = res.data;

            const data = data1.filter(item => {
              const time = '2021-08-20';
              // const time = '2021-08-19';
              // 列表过滤日期(暂时)
              if (item.createTime) {
                // return item.createTime.startsWith('2021-08-19');
                return item.createTime.startsWith(time);
              }

              if (item.startedDate) {
                // return item.startedDate.startsWith('2021-08-19');
                return item.startedDate.startsWith(time);
              }
              return 1;
            });
            for (let i = 0; i < data.length; i++) {
              const item = data[i];
              if (flag) {
                if (item.bizKey) {
                  const { success, data: myQuery } = await findModelInfoByFormGuid({
                    formGuid: item.bizKey
                  });

                  if (success) {
                    const {
                      name,
                      // createTime,
                      sId
                    } = myQuery;

                    Object.assign(item, {
                      myQuery,
                      // createTime,
                      sId,
                      modelName: name
                    });
                  }

                  tabNow.dataList.push(item);
                }
              }
            }

            if (!flag) {
              tabNow.dataList = [...dataList, ...data];
            }
          }
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.StatisticCenter {
  width: 100%;
  height: 100%;
  .tapsStyle {
    background-color: #fff;
  }

  .StatisticCenter_container {
    height: calc(100% - 44px - 3px);
    margin-top: 3px;
    overflow: auto;

    .searchFilter {
      padding: 12px 16px;
    }

    .commonlist-content {
      height: 100%;
      overflow: auto;
    }
  }
}

/deep/ .StatisticCell {
  .myCell {
    color: #333;
    display: flex;
    padding: 12px 16px;
    background-color: #fff;
    height: 40px;
    align-items: center;
    position: relative;

    .myCell-left {
      flex: 4;
      font-size: 18px;

      .label {
        display: flex;
        .cw_tip {
          background-color: #73D13D;
          border-radius: 4px;
          font-size: 12px;
          color: #fff;
          padding: 4px;
          width: 15px;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-left: 8px;
        }

        .label_font {
          max-width: 250px;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
        }
      }

    }

    .myCell-right {
      flex: 1;
      text-align: right;
    }

    .myCell-tip {
      margin-top: 6px;
      color: #BCBCBC;
      font-size: 12px;
    }

    &.border-line {
      &.pb-s::after,
      &.pt::before,
      &.pb::after
      {
        content: '';
        display: block;
        position: absolute;
        left: 12px;
        right: 0;
        height: 1px;
        background-color: #E5E5E5;
      }

      &.pt::before {
        top: 0;
        left: 0;
      }

      &.pb::after {
        bottom: 0;
        left: 0;
      }

      &.pb-s::after {
        bottom: 0;
      }
    }
  }
}

</style>
